package easier.app.x.crash;

import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * handle crash for ui_thread and other_thread
 * app 崩溃管理
 */
public class CrashWatcher {

    /**
     * flag for started
     */
    private final AtomicBoolean started = new AtomicBoolean( false );

    public void start() {

        loopMain();

        /* other thread exception */
        Thread.setDefaultUncaughtExceptionHandler( new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException( @NonNull Thread t, @NonNull Throwable e ) {

                CrashWatcher.this.uncaughtException( t, e );
            }
        } );
    }

    /**
     * 处理非主线程异常
     *
     * @param t 线程
     * @param e 异常
     */
    protected void uncaughtException( @NonNull Thread t, @NonNull Throwable e ) {

    }

    private void loopMain() {

        if ( started.get() ) {
            return;
        }

        started.set( true );

        new Handler( Looper.getMainLooper() ).post( new Runnable() {
            @Override
            public void run() {

                /*ui thread exception*/
                for ( ; ; ) {
                    try {
                        Looper.loop();
                    } catch ( Exception e ) {
                        CrashWatcher.this.uncaughtException( Looper.getMainLooper().getThread(), e );
                    }
                }
            }
        } );
    }
}